package foundation.tree.binaryTree.二叉树的序列化与反序列化;


import java.util.LinkedList;
import java.util.Queue;

/**
 * @author hang an
 * @since 2025/7/12
 */
public class 层序 {
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        enF(root, sb);
        System.out.println(sb);
        return sb.toString();
    }

    public void enF(TreeNode node, StringBuilder sb) {
        if (node == null) {
            sb.append("#,");
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(node);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode cur = queue.poll();
                if (cur == null) {
                    sb.append("#,");
                    continue;
                }
                sb.append(cur.val).append(",");
                queue.add(cur.left);
                queue.add(cur.right);
            }
        }
    }


    public TreeNode deserialize(String data) {
        String[] allNode = data.split(",");
        int index = 1;
        String first = allNode[0];
        if (first.equals("#")) return null;
        TreeNode root = new TreeNode(Integer.parseInt(first));
        TreeNode left = root;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (index < allNode.length) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode curFather = queue.poll();
                String leftNode = allNode[index++];
                if (!leftNode.equals("#")) {
                    curFather.left = new TreeNode(Integer.parseInt(leftNode));
                    queue.add(curFather.left);
                }
                String rightNode = allNode[index++];
                if (!rightNode.equals("#")) {
                    curFather.right = new TreeNode(Integer.parseInt(rightNode));
                    queue.add(curFather.right);
                }
            }

        }
        return root;
    }


}
